package net.simflow.swf.analyzer.gui.opt;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.widgets.Text;

public class TextOperater {

	private static TextOperater instance = new TextOperater();

	private TextOperater() {
	}

	public static TextOperater getInstance() {
		return instance;
	}

	public void addVerify(final Text text, final String regex, int limit) {
		text.setTextLimit(limit);
		text.addVerifyListener(new VerifyListener() {
			public void verifyText(VerifyEvent e) {
				Pattern pattern = Pattern.compile(regex);
				String str = text.getText().substring(0, text.getSelection().x)
						+ e.text
						+ text.getText().substring(text.getSelection().y,
								text.getText().length());
				Matcher matcher = pattern.matcher(str);
				if (matcher.matches())
					e.doit = true;
				else if (e.text.length() > 0)
					e.doit = false;
				else
					e.doit = true;
			}
		});
	}
}
